from rest_framework import serializers
from .models import User, UserProfile
import pdb

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = UserProfile
        fields = '__all__'


class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True,
                                     required=True,
                                     style={'input_type': 'password'},
                                     min_length=8,
                                     help_text='至少8个字符',
                                     error_messages={
                                        'min_length': '密码必须至少包含8个字符。',
                                        'required': '密码不能为空。',
                                     }
                                    )
    class Meta:
        model = User
        fields = '__all__'

        extra_kwargs = {
            'username': {
                'error_messages': {
                    'unique': '此用户名已被使用，请选择另一个用户名。',
                    'invalid': '请输入有效的用户名。',
                    'required': '用户名不能为空。',
                }
            },
        }

    def validate_username(self, value):

        pdb.set_trace()
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError('该用户已注册')
        return value


    def create(self, validated_data):
        user = User.objects.create_user(username=validated_data['username'],
                                        password=validated_data['password'])
        return user